//
//  NSArray+SLAdd.m
//  shunlianPower2
//
//  Created by lengain on 2019/10/10.
//  Copyright © 2019 顺联网络. All rights reserved.
//

#import "NSArray+SLAdd.h"
#import "NSDictionary+SLAdd.h"
#import "SLCategoriesRuntime.h"
@implementation NSArray (SLAdd)

// Swizzling核心代码
// 需要注意的是，好多同学反馈下面代码不起作用，造成这个问题的原因大多都是其调用了super load方法。在下面的load方法中，不应该调用父类的load方法。
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class myClass = objc_getClass("__NSArrayI");
        SLExchangeImplementations(myClass, @selector(objectAtIndex:), @selector(sl_objectAtIndex:));
        SLExchangeImplementations(myClass, @selector(objectAtIndexedSubscript:), @selector(sl_objectAtIndexedSubscript:));
    });
}

- (id)sl_objectAtIndexedSubscript:(NSUInteger)index {
    
    @autoreleasepool {
        // 判断下标是否越界，如果越界就进入异常拦截
         if (self.count==0|| self.count-1 < index) {
            @try {
                return [self sl_objectAtIndexedSubscript:index];
            }
            @catch (NSException *exception) {
                // 在崩溃后会打印崩溃信息。如果是线上，可以在这里将崩溃信息发送到服务器
                NSLog(@"---------- %s 数组越界 Crash Because Method %s  ----------\n", class_getName(self.class), __func__);
                NSLog(@"%@", [exception callStackSymbols]);
                return nil;
            }
            @finally {}
        } // 如果没有问题，则正常进行方法调用
        else {
            return [self sl_objectAtIndexedSubscript:index];
        }
    }
    
}
// 为了避免和系统的方法冲突，我一般都会在swizzling方法前面加前缀
- (id)sl_objectAtIndex:(NSUInteger)index {
    @autoreleasepool {
        // 判断下标是否越界，如果越界就进入异常拦截
         if (self.count==0|| self.count-1 < index) {
            @try {
                return [self sl_objectAtIndex:index];
            }
            @catch (NSException *exception) {
                // 在崩溃后会打印崩溃信息。如果是线上，可以在这里将崩溃信息发送到服务器
                NSLog(@"---------- %s 数组越界 Crash Because Method %s  ----------\n", class_getName(self.class), __func__);
                NSLog(@"%@", [exception callStackSymbols]);
                return nil;
            }
            @finally {}
        } // 如果没有问题，则正常进行方法调用
        else {
            return [self sl_objectAtIndex:index];
        }
    }
}



- (NSArray *)sl_judegNull:(NSArray *)arrray{
    NSMutableArray *tmp = [NSMutableArray array];
    for (id dic in arrray) {
        NSString *className =NSStringFromClass([dic class]);
        if ([className rangeOfString:@"NSDictionary"].location != NSNotFound ||[dic class] == [NSDictionary class]) {
            NSDictionary *tmpDic = [(NSDictionary *)dic sl_judegNull];
            if ([tmpDic allKeys].count>0) {
                [tmp addObject:[dic sl_judegNull]];
            }
        }else if([className rangeOfString:@"NSArray"].location != NSNotFound||[dic class] == [NSDictionary class]){
            
            NSArray *arrya = dic;
            NSArray *tmpArray = [self sl_judegNull:arrya];
            if (tmpArray.count>0) {
                [tmp addObject:tmpArray];
            }
        }else if([className rangeOfString:@"String"].location != NSNotFound||[className rangeOfString:@"Number"].location != NSNotFound){
            NSString *value = [NSString stringWithFormat:@"%@",dic];
            
            if (![value isEqualToString:@"<null>"] && ![value isEqualToString:@"(null)"]) {
                NSString *value = [NSString stringWithFormat:@"%@",dic];
                [tmp addObject:value];
            }
        }else{
            //不是数组 不是字典 不是字符串 不是数字 -----暂不处理
        }
    }
    if (tmp.count==0) {
        return nil;
    }
    return tmp;
}

#ifdef DEBUG

- (NSString *)description {
    return [self sl_descriptionWithLevel:1];
}

-(NSString *)sl_descriptionWithLocale:(id)locale{
    return [self sl_descriptionWithLevel:1];
}

- (NSString *)sl_descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level {
    return [self sl_descriptionWithLevel:(int)level];
}

/**
 将数组转化成字符串，文字格式UTF8,并且格式化
 
 @param level 当前数组的层级，最少为 1，代表最外层
 @return 格式化的字符串
 */
- (NSString*)sl_descriptionWithLevel:(int)level {
    NSString *subSpace = [self sl_getSpaceWithLevel:level];
    NSString *space = [self sl_getSpaceWithLevel:level -1];
    NSMutableString *retString = [[NSMutableString alloc]init];
    // 1、添加 [
    [retString appendString:[NSString stringWithFormat:@"["]];
    // 2、添加 value
    [self enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *value = (NSString*)obj;
            value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSString *subString = [NSString stringWithFormat:@"\n%@\"%@\",", subSpace, value];
            [retString appendString:subString];
        }else if ([obj isKindOfClass:[NSArray class]]) {
            NSArray *arr = (NSArray*)obj;
            NSString *str = [arr sl_descriptionWithLevel:level +1];
            str = [NSString stringWithFormat:@"\n%@%@,", subSpace, str];
            [retString appendString:str];
        }else if ([obj isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = (NSDictionary*)obj;
            NSString *str = [dic sl_descriptionWithLocale:nil indent:level +1];
            str = [NSString stringWithFormat:@"\n%@%@,", subSpace, str];
            [retString appendString:str];
        }else {
            NSString *subString = [NSString stringWithFormat:@"\n%@%@,", subSpace, obj];
            [retString appendString:subString];
        }
    }];
    if ([retString hasSuffix:@","]) {
        [retString deleteCharactersInRange:NSMakeRange(retString.length-1,1)];
    }
    // 3、添加 ]
    [retString appendString:[NSString stringWithFormat:@"\n%@]", space]];
    return retString;
}


/**
 根据层级，返回前面的空格占位符
 
 @param level 层级
 @return 占位空格
 */
- (NSString*)sl_getSpaceWithLevel:(int)level {
    NSMutableString *mustr = [[NSMutableString alloc]init];
    for (int i=0; i<level; i++) {
        [mustr appendString:@"\t"];
    }
    return mustr;
}

#endif

@end
